<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.deviceid"
        placeholder="请输入内容"
        style="width:350px;height:14px;padding-top:10px;padding-bottom:10px;margin-left:10px;margin-bottom:10px;">
        <el-select slot="prepend" v-model="listQuery.selectColumn" placeholder="请选择" style="width:120px;height:14px;">
          <el-option label="传感器ID" value="deviceid"/>
        </el-select>
      </el-input>
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%">
      <el-table-column width="110" align="center" label="传感器图像">
        <template slot-scope="scope">
          <img :src="scope.row.imagesshot" style="height:auto;width:100%;">
        </template>
      </el-table-column>
      <el-table-column width="100" align="center" label="传感器Id">
        <template slot-scope="scope">
          <span>{{ scope.row.deviceid }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" align="center" label="传感器位置">
        <template slot-scope="scope">
          <span>{{ scope.row.location }}</span>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="传感器名称">
        <template slot-scope="scope">
          <span>{{ scope.row.categoryname }}</span>
        </template>
      </el-table-column>
      <el-table-column width="150" align="center" label="传感器分类名称">
        <template slot-scope="scope">
          <span>{{ scope.row.categoryname }}</span>
        </template>
      </el-table-column>
      <!--<el-table-column width="110" align="center" label="传感器规格">
        <template slot-scope="scope">
          <span>{{ scope.row.specication }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" align="center" label="传感器设施id">
        <template slot-scope="scope">
          <span>{{ scope.row.assetid }}</span>
        </template>
      </el-table-column>-->
      <el-table-column width="120" align="center" label="传感器关联">
        <template slot-scope="scope">
          <span>{{ scope.row.assigntoken==null &&'未关联' ||'已经关联' }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.actions')" fixed="right" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button v-if="scope.row.assigntoken==null" type="danger" size="mini" @click="handleDelete(scope.row)">{{ $t('table.delete') }}</el-button>
          <el-button v-if="scope.row.assigntoken==null" type="primary" size="mini" @click="handleBinding(scope.row)">{{ $t('table.binding') }}</el-button>
          <el-button v-else type="primary" size="mini" @click="unBinding(scope.row)">{{ $t('table.unbind') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        :current-page.sync="listQuery.page"
        :page-sizes="[10,20,30, 50]"
        :page-size="listQuery.limit"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>

    <!-- 增加及修改页 -->
    <el-dialog :title="textMap[dialogStatus]" :fullscreen="false" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="120px" style="width: 450px; margin-left:50px;">
        <template v-if="dialogStatus == 'update'">
          <el-form-item label="传感器Id" prop="deviceid">
            <el-input v-model="temp.deviceid" :disabled="true"/>
          </el-form-item>
          <el-form-item label="传感器位置" prop="location">
            <el-input v-model="temp.location"/>
          </el-form-item>
          <!--           <el-form-item label="父传感器id" prop="parentHardwareId">
            <el-input v-model="temp.parentHardwareId" />
          </el-form-item>
          <el-form-item label="是否移除父传感器id" prop="removeParentHardwareId">
            <el-input v-model="temp.removeParentHardwareId"/>
          </el-form-item>
          <el-form-item label="站点token" prop="siteid">
            <el-input v-model="temp.siteid"/>
          </el-form-item>
          <el-form-item label="传感器规格" prop="specication">
            <el-input v-model="temp.specication"/>
          </el-form-item> -->
        </template>
        <template v-if="dialogStatus == 'binding'">
          <el-form-item label="传感器Id" prop="deviceid">
            <el-input v-model="temp.deviceid" :disabled="true"/>
          </el-form-item>

          <el-form-item label="传感器资产" prop="id">
            <el-select v-model="temp.id" placeholder="传感器资产名称+位置">
              <el-option v-for="item in AssetList" :key="item.id" :label="item.name+'@'+item.properties.Alocation" :value="item.id"/>
            </el-select>
          </el-form-item>
        </template>

        <template v-if="dialogStatus == 'unbind'">
          <el-form-item label="传感器Id" prop="deviceid">
            <el-input v-model="temp.deviceid" :disabled="true"/>
          </el-form-item>
          <el-form-item label="传感器关联" prop="assigntoken">
            <el-input v-model="temp.assigntoken" :disabled="true"/>
          </el-form-item>
        </template>

        <template v-if="dialogStatus == 'create'">
          <el-form-item label="传感器Id" prop="deviceid">
            <el-input v-model="temp.deviceid" placeholder="传感器id"/>
          </el-form-item>
          <el-form-item label="分类名称" prop="categoryid">
            <el-select v-model="temp.categoryid" placeholder="传感器分类名称">
              <el-option v-for="item in stOptions" :key="item.categoryid" :label="item.categoryname" :value="item.categoryid"/>
            </el-select>
          </el-form-item>
          <el-form-item label="传感器位置" prop="location">
            <el-input v-model="temp.location" placeholder="列如：现代大厦4楼"/>
          </el-form-item>
        </template>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{ $t('table.confirm') }}</el-button>
        <el-button v-if="dialogStatus=='binding'" type="primary" @click="bindingData">{{ $t('table.confirm') }}</el-button>
        <el-button v-if="dialogStatus=='update'" type="primary" @click="updateData">{{ $t('table.confirm') }}</el-button>
        <el-button v-if="dialogStatus=='unbind'" type="primary" @click=" unbindingData">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addDevice,
  assetList,
  assignDevice,
  cancelAssignDevice,
  deleteAssignDevice,
  deleteDevice,
  getDeviceCategory,
  getDeviceDetail,
  getDeviceList,
  updateDevice
} from '@/api/fire/device/device'
import waves from '@/directive/waves' // 水波纹指令
export default {
  name: 'Ddd',
  directives: {
    waves
  },
  data() {
    return {
      expandAll: false,
      tableKey: 0,
      assetTableKey: 0,
      myAssetTableKey: 0,
      list: null,
      assetList: null,
      myAssetList: null,
      total: null,
      listLoading: true,
      treeSelectedOptions: [],
      maintainorOptions: [],
      supervisorOptions: [],
      proprietorOptions: [],
      stOptions: [],
      AssetList: [],
      devicedetail: [],
      listQuery: {
        page: 1,
        pagesize: 10,
        siteid: this.$store.state.asset.siteid,
        selectColumn: '',
        columnValue: '',
        deviceid: '',
        token: 'f466905c'
      },
      // sexOptions: getDictList('sex'),
      showReviewer: false,
      temp: {
        categoryid: '',
        page: 1,
        pagesize: 10,
        deviceid: '',
        location: '',
        imagesshot: '',
        devicecategoryid: '',
        specication: '',
        siteid: this.$store.state.asset.siteid,
        parentHardwareId: '',
        removeParentHardwareId: '',
        categoryurl: '',
        categoryname: '',
        id: '',
        name: '',
        properties: '',
        Alocation: '',
        assigntoken: ''
      },
      dialogFormVisible: false,
      dialogAssetFormVisible: false,
      dialogDeviceFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改传感器',
        create: '添加传感器',
        binding: '传感器指派资产',
        unbind: '取消传感器资产关联'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        removeParentHardwareId: [{ required: true, message: '是否移除父传感器ID（true or false）', trigger: 'blur' }]

      },
      downloadLoading: false,
      permissionTreeList: null,
      permissionQuery: {
        sort: '+id'
      },
      buttonInit: [
        {
          title: '查询',
          permission: 'list'
        },
        {
          title: '添加',
          permission: 'add'
        },
        {
          title: '更新',
          permission: 'update'
        },
        {
          title: '删除',
          permission: 'delete'
        },
        {
          title: '导出',
          permission: 'export'
        },
        {
          title: '导入',
          permission: 'import'
        }
      ]
    }
  },
  created() {
    this.getList()
    this.getDeviceCategory()
    this.getAssetList()
  },
  methods: {
    changeRoute() {
      this.$store.dispatch('ChangeRoute')
      this.$store.commit('BACK_VISIBLE', true)
    },
    getList() {
      this.listLoading = true
      getDeviceList(this.listQuery).then(response => {
        this.list = response.data.context
        console.log('获取到都对象数组', this.list)
        // this.total = response.data.context.total
        this.listLoading = false
      })
    },
    changeRequireAuth() {

    },
    handleFilter() {
      // this.getList()
      this.querydevice()
    },
    getAssetList() {
      assetList(this.temp).then(response => {
        console.log('资产返回消息', response)
        this.AssetList = response.data.context.assetlists
      })
    },
    getDeviceCategory() {
      getDeviceCategory().then(response => {
        this.stOptions = response.data.context.devicecategorylist
      })
    },
    querydevice() {
      if (this.listQuery.deviceid === '') {
        console.log('=============', this.listQuery.deviceid)
        this.getList()
      } else {
        console.log('请求获取到设备详情', this.listQuery)
        getDeviceDetail(this.listQuery).then(response => {
          console.log('获取到设备详情', response)
          if (response.data.status === '0') {
            this.list = response.data.context
          }
        })
      }
    },
    resetTemp() {
      this.temp = {
        categoryid: '',
        token: '',
        page: 1,
        pagesize: 100,
        deviceid: '',
        location: '',
        imagesshot: '',
        devicecategoryid: '',
        specication: '',
        siteid: '',
        parentHardwareId: '',
        removeParentHardwareId: '',
        categoryurl: '',
        categoryname: '',
        id: '',
        name: '',
        properties: '',
        Alocation: '',
        assigntoken: ''
      }
      this.treeSelectedOptions.length = 0
    },
    handleCreate() {
      this.resetTemp()
      this.changeRequireAuth()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleBinding(row) {
      this.resetTemp()
      this.temp = Object.assign({}, row) // copy obj
      this.changeRequireAuth()
      this.dialogStatus = 'binding'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    unBinding(row) {
      this.resetTemp()
      this.temp = Object.assign({}, row) // copy obj
      this.changeRequireAuth()
      this.dialogStatus = 'unbind'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData: function() {
      // 预处理提交的数据
      for (const optionObj in this.buildingOptions) {
        if (this.buildingOptions[optionObj].key === this.temp.buildingid) {
          this.temp.buildingname = this.buildingOptions[optionObj].value
        }
      }
      for (const optionObj in this.supervisorOptions) {
        if (this.supervisorOptions[optionObj].value === this.temp.supervisorid) {
          this.temp.supervisorname = this.supervisorOptions[optionObj].label
        }
      }
      for (const optionObj in this.maintainorOptions) {
        if (this.maintainorOptions[optionObj].key === this.temp.maintainor) {
          this.temp.maintainname = this.maintainorOptions[optionObj].value
        }
      }
      for (const optionObj in this.proprietorOptions) {
        if (this.proprietorOptions[optionObj].key === this.temp.proprietor) {
          this.temp.proprietorname = this.proprietorOptions[optionObj].value
        }
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // if (this.temp.parentIds !== undefined && this.temp.parentIds !== '') {
          //   this.temp.parentIds.length = 0
          // }
          this.temp.siteid = this.$store.state.asset.siteid
          addDevice(this.temp).then((response) => {
            console.log('==================', this.temp)
            const data = response.data
            if (data.status === '0') {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '增加成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            } else {
              this.$notify({
                title: '失败',
                message: data.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.resetTemp()
      this.temp = Object.assign({}, row) // copy obj
      this.changeRequireAuth()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateDevice(tempData).then((response) => {
            console.log('更新都数据', response)
            const data = response.data
            if (data.status === '0') {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: data.msg,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },

    bindingData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          assignDevice(tempData).then((response) => {
            console.log('绑定数据', response)
            const data = response.data
            if (data.status === '0') {
              this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '绑定成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify({
                title: '失败',
                message: data.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    unbindingData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          console.log('请求释放关联都参数', tempData)
          // 请求释放关联接口
          cancelAssignDevice(tempData).then((response) => {
            console.log('释放绑定数据', response)
            const data = response.data
            if (data.status === '0') {
              this.getList()
              this.dialogFormVisible = false
              // 请求删除关联接口
              deleteAssignDevice(tempData).then((response) => {
                console.log('删除绑定数据', response)
                const data = response.data
                if (data.status === '0') {
                  this.getList()
                  this.dialogFormVisible = false
                  // 请求删除关联接口
                  this.$notify({
                    title: '成功',
                    message: '解绑成功',
                    type: 'success',
                    duration: 2000
                  })
                } else {
                  this.$notify({
                    title: '失败',
                    message: data.message,
                    type: 'error',
                    duration: 2000
                  })
                }
              })
            } else {
              this.$notify({
                title: '失败',
                message: data.message,
                type: 'error',
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认要删除传感器么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log('设备id', row.deviceid)
        deleteDevice(row).then(response => {
          console.log('删除传感器', response)
          const data = response.data
          if (data.status === '0') {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          } else {
            this.$notify({
              title: '失败',
              message: data.tips,
              type: 'error',
              duration: 2000
            })
          }
        })
      })
    },
    // queryMaintainorOptions() {
    //   getMaintainorSelectItem().then(response => {
    //     if (response.data.status === '0') {
    //       this.maintainorOptions = response.data.context
    //     }
    //   })
    // },
    handleSizeChange(val) {
      this.listQuery.pagesize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    }

  }
}
</script>
<style>
  .select-width-100{
    width: 100%;
  }
</style>
